package com.meeting.y.controller;
//Created by lb.kong on 2020/11/22.

import com.jfinal.aop.Duang;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.cache.IAccessTokenCache;
import com.jfinal.wxaapp.api.WxaUserApi;
import com.jfinal.wxaapp.jfinal.WxaController;
import com.meeting.y.model.PaperDao;
import com.meeting.y.model.WechatUser;
import com.meeting.y.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * 微信小程序用户api接口
 * @author L.cm
 */
public class WxaUserApiController extends WxaController {
    private static final Logger logger = LoggerFactory.getLogger(WxaUserApiController.class);

    /**
     * 登陆接口
     */
    public void login() {
        String jsCode = getPara("code");
        if (StrKit.isBlank(jsCode)) {
            Kv data = Kv.by("errcode", 500)
                    .set("errmsg", "code is blank");
            renderJson(data);
            return;
        }
        // 获取SessionKey
        ApiResult apiResult = WxaUserApi.getSessionKey(jsCode);
        // 返回{"session_key":"nzoqhc3OnwHzeTxJs+inbQ==","expires_in":2592000,"openid":"oVBkZ0aYgDMDIywRdgPW8-joxXc4"}
        if (!apiResult.isSucceed()) {
            renderJson(apiResult.getJson());
            return;
        }
        // 利用 appId 与 accessToken 建立关联，支持多账户
        IAccessTokenCache accessTokenCache = ApiConfigKit.getAccessTokenCache();
        String sessionId = StrKit.getRandomUUID();

        accessTokenCache.set("wxa:session:" + sessionId, apiResult.getJson());
        logger.debug(" wxa:session 放入cache中，设置cookies:" + sessionId);

        setCookie("wxa-sessionid", sessionId, 15 * 24 * 3600, true);


        renderJson("sessionId", sessionId);
    }

    /**
     * 服务端解密用户信息接口
     * 获取unionId
     */
    public void info() {
        String signature = getPara("signature");
        String rawData = getPara("rawData");

        String encryptedData = getPara("encryptedData");
        String iv = getPara("iv");

        // 参数空校验 不做演示
        // 利用 appId 与 accessToken 建立关联，支持多账户
        IAccessTokenCache accessTokenCache = ApiConfigKit.getAccessTokenCache();
        String sessionId = getHeader("wxa-sessionid");
        if (StrKit.isBlank(sessionId)) {
            Kv data = Kv.by("errcode", 500)
                    .set("errmsg", "wxa_session Header is blank");
            renderJson(data);
            return;
        }
        String sessionJson = accessTokenCache.get("wxa:session:" + sessionId);
        if (StrKit.isBlank(sessionJson)) {
            Kv data = Kv.by("errcode", 500)
                    .set("errmsg", "wxa_session sessionJson is blank");
            renderJson(data);
            return;
        }
        ApiResult sessionResult = ApiResult.create(sessionJson);
        // 获取sessionKey
        String sessionKey = sessionResult.get("session_key");
        if (StrKit.isBlank(sessionKey)) {
            Kv data = Kv.by("errcode", 500)
                    .set("errmsg", "sessionKey is blank");
            renderJson(data);
            return;
        }
        // 用户信息校验
        boolean check = WxaUserApi.checkUserInfo(sessionKey, rawData, signature);
        if (!check) {
            Kv data = Kv.by("errcode", 500)
                    .set("errmsg", "UserInfo check fail");
            renderJson(data);
            return;
        }
        //若有sessionkey 直接返回
        WechatUser _wechatUser = WechatUser.dao.findWechatuserBySessionKey(sessionKey);
        if (_wechatUser != null) {
            renderJson(Ret.ok("code", 0).set("message", "返回成功")
                    .set("data", new YmeetingController().getUserInfo(_wechatUser)));
            return;
        }

        // 服务端解密用户信息
        ApiResult apiResult1 = WxaUserApi.getUserInfo(sessionKey, encryptedData, iv);
        if (!apiResult1.isSucceed()) {
            renderJson(apiResult1.getJson());
            return;
        }
        // 如果开发者拥有多个移动应用、网站应用、和公众帐号（包括小程序），可通过unionid来区分用户的唯一性
        // 同一用户，对同一个微信开放平台下的不同应用，unionid是相同的。
        String unionId = apiResult1.get("unionId");

        /**
         * {"openId":"oo4fI5fQG0sbGJxFI0g3azGgMBzA",
         * "nickName":"孔令宝-携宁科技","gender":1,"language":"zh_CN","city":"徐汇","province":"上海","country":"中国",
         * "avatarUrl":"https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJBYseJziapAgJZTBWMvUUKa4k9ia4Xf747FMGKlm8NDCxcvlwPBatofxyHwqPXnN0u12RvhK2X1pLA/132",
         * "watermark":{"timestamp":1571119870,"appid":"wxaf9a125026464d06"}}
         */
        String openid = apiResult1.get("openId");
        WechatUser wechatUser = WechatUser.dao.findWechatuser(openid);
        if (wechatUser == null) {
            wechatUser = new WechatUser();
        }
        wechatUser.setSessionKey(sessionKey);
        wechatUser.setNickname(apiResult1.getStr("nickName"));
        wechatUser.setAvatarurl(apiResult1.getStr("avatarUrl"));
        wechatUser.setCity(apiResult1.getStr("city"));
        wechatUser.setGender(apiResult1.getInt("gender"));
        wechatUser.setLanguage(apiResult1.getStr("language"));
        wechatUser.setCountry(apiResult1.getStr("country"));
        wechatUser.setProvince(apiResult1.getStr("province"));
        wechatUser.setMobile(StringUtil.valueOf(apiResult1.getStr("mobile")));
        wechatUser.setOpenid(apiResult1.getStr("openId"));
        if (wechatUser.getNickname().equals("孔令宝-携宁科技") ||
                wechatUser.getNickname().equals("冷丁")) {
            wechatUser.setRelaUserId(1);
            wechatUser.setRelaUserDesc("管理员");
        }
        wechatUser.setUnionid(StringUtil.valueOf(unionId));
        wechatUser.setModifyTime(new Date());
        if (wechatUser.getId() == null) {
            wechatUser.save();
            try {
                Record user = new Record();
                user.set("userid", wechatUser.getId()); //wechat_user.id = user.userid
                user.set("avatarUrl", wechatUser.getAvatarurl());
                user.set("city", wechatUser.getCity());
                user.set("country", wechatUser.getCountry());
                user.set("credit", 0);//积分
                user.set("gender", wechatUser.getGender());
                user.set("nickName", wechatUser.getNickname());
                user.set("openid", wechatUser.getOpenid());
                user.set("province", wechatUser.getProvince());
                user.set("sessionKey", wechatUser.getSessionKey());
                PaperDao.dao.saveUser(user);
            }catch (Exception e){
                logger.error("同步用户到user报错",e);
            }
        } else {
            wechatUser.update();
        }

// 下方为模拟数据：
        logger.info("encrypted_data:"+encryptedData);

        renderJson(Ret.ok("code", 0).set("message", "返回成功")
                .set("data", new YmeetingController().getUserInfo(wechatUser)));
        return;

    }

}

